# Direct outputs eligible for public release

# GLOBAL SETTINGS --------------------------------------------------------------

options(
  scipen = 999,
  digits = 16,
  max.print = .Machine$integer.max,
  show.error.locations = TRUE,
  warn = 1
)

RNGkind("L'Ecuyer-CMRG")
seed <- 818675309L
set.seed(seed) # setting main seed

# PACKAGES ---------------------------------------------------------------------

library(data.table)

# PACKAGE SETTINGS -------------------------------------------------------------

# data.table
setDTthreads(threads = 1)
options(datatable.print.class = TRUE, datatable.print.keys = TRUE)
# so that printing the data.table also shows the variable type on top

# BEGIN FILE -------------------------------------------------------------------

# Just in case something masks 'source()', use extra deliberate base::source().
base::source("~/code/0-utility-functions/table-and-text-utils.R", local = TRUE)

# READ IN OUR DATA -------------------------------------------------------------

# Focus on the aggregate (+1 to +5) estimates (event_time == 99) throughout

db_w2_wages_dt <-
    readRDS("~/estimation-output/wealth_effect_estimates_db_w2_wages.rds")
setnames(db_w2_wages_dt, "ref_event_time", "event_time")
db_w2_wages_dt <- db_w2_wages_dt[event_time == 99]

per_adult_w2_wages_dt <-
    readRDS("~/estimation-output/wealth_effect_estimates_per_adult_w2_wages.rds")
setnames(per_adult_w2_wages_dt, "ref_event_time", "event_time")
per_adult_w2_wages_dt <- per_adult_w2_wages_dt[event_time == 99]

per_adult_total_empl_income_dt <-
    readRDS("~/estimation-output/wealth_effect_estimates_per_adult_total_empl_income.rds") #nolint
setnames(per_adult_total_empl_income_dt, "ref_event_time", "event_time")
per_adult_total_empl_income_dt <-
    per_adult_total_empl_income_dt[event_time == 99]

per_adult_capital_income_dt <-
    readRDS("~/estimation-output/wealth_effect_estimates_per_adult_capital_income.rds") #nolint
setnames(per_adult_capital_income_dt, "ref_event_time", "event_time")
per_adult_capital_income_dt <- per_adult_capital_income_dt[event_time == 99]

has_w2_wages_dt <-
    readRDS("~/estimation-output/wealth_effect_estimates_has_w2_wages.rds")
setnames(has_w2_wages_dt, "ref_event_time", "event_time")
has_w2_wages_dt <- has_w2_wages_dt[event_time == 99]

# Total Employment actually estimated as non-employment
# so just adjust by multiplying by -1
total_employment_dt <-
    readRDS("~/estimation-output/wealth_effect_estimates_total_employment.rds")
setnames(total_employment_dt, "ref_event_time", "event_time")
total_employment_dt <- total_employment_dt[event_time == 99]
total_employment_dt[, estimate := (-1) * estimate]

# MAKE TABLE -------------------------------------------------------------------

filedir <- "~/paper/tables/table-3.1.tex"
file.create(filedir)

# Start Table 3.1
start_latex_table(
    column_structure = "cccccccc",
    file_dir = filedir,
    append = TRUE
)
add_latex_table_rule(rule_type = "toprule", file_dir = filedir, append = TRUE)
add_latex_table_rule(rule_type = "midrule", file_dir = filedir, append = TRUE)

heading_text_input1 <-
    " &  & \\multicolumn{6}{c}{Sample} "
write_latex_table_row(heading_text_input1, file_dir = filedir, append = TRUE)

add_latex_cmidrule(
    point_start_col = "l",
    point_end_col = "r",
    start_col = 3,
    end_col = 8,
    file_dir = filedir,
    append = TRUE
)

heading_text_input2 <-
    " \\multirow{3}{*}{Outcome} & & \\multirow{2}{*}{Full Sample} & & Quartile 1  &  Quartile 2 & Quartile 3 & Quartile 4 " #nolint
write_latex_table_row(heading_text_input2, file_dir = filedir, append = TRUE)

heading_text_input3 <-
    "  & & & & Pre-Win Income  &  Pre-Win Income & Pre-Win Income & Pre-Win Income " #nolint
write_latex_table_row(heading_text_input3, file_dir = filedir, append = TRUE)

heading_text_input4 <-
    "  & & (1) & & (2) & (3) & (4) & (5) " #nolint
write_latex_table_row(heading_text_input4, file_dir = filedir, append = TRUE)

heading_text_input1 <- NULL
heading_text_input2 <- NULL
heading_text_input3 <- NULL
heading_text_input4 <- NULL
rm(
    heading_text_input1,
    heading_text_input2,
    heading_text_input3,
    heading_text_input4
)

add_latex_table_rule(rule_type = "midrule", file_dir = filedir, append = TRUE)
write_latex_table_row(
        " & & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# Add body of Table 3.1
# - introduce convenience functions given a similar structure throughout

Table31Row1 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            "%s & & %s & & %s & %s & %s & %s",
            text,
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 5]$estimate,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 1]$estimate,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 2]$estimate,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 3]$estimate,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 4]$estimate,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

Table31Row2 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            "%s & & (%s) & & (%s) & (%s) & (%s) & (%s)",
            text,
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 5]$cluster_se,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 1]$cluster_se,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 2]$cluster_se,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 3]$cluster_se,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[income_quartile == 4]$cluster_se,
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

# Winner Wage Earnings
Table31Row1(
    dt = db_w2_wages_dt,
    text = "Winner Wage Earnings",
    scaler = 100
)
Table31Row2(
    dt = db_w2_wages_dt,
    text = "(per \\$100)",
    scaler = 100
)
write_latex_table_row(
        " & & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# Per-Adult Wage Earnings
Table31Row1(
    dt = per_adult_w2_wages_dt,
    text = "Per-Adult Wage Earnings",
    scaler = 100
)
Table31Row2(
    dt = per_adult_w2_wages_dt,
    text = "(per \\$100)",
    scaler = 100
)
write_latex_table_row(
        " & & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# Per-Adult Total Labor Earnings
Table31Row1(
    dt = per_adult_total_empl_income_dt,
    text = "Per-Adult Total Labor Earnings",
    scaler = 100
)
Table31Row2(
    dt = per_adult_total_empl_income_dt,
    text = "(per \\$100)",
    scaler = 100
)
write_latex_table_row(
        " & & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# Per-Adult Capital Income
Table31Row1(
    dt = per_adult_capital_income_dt,
    text = "Per-Adult Capital Income",
    scaler = 100
)
Table31Row2(
    dt = per_adult_capital_income_dt,
    text = "(per \\$100)",
    scaler = 100
)
write_latex_table_row(
        " & & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# Winner Employment
Table31Row1(
    dt = has_w2_wages_dt,
    text = "Winner Employment",
    scaler = 100000
)
Table31Row2(
    dt = has_w2_wages_dt,
    text = "(per \\$100,000)",
    scaler = 100000
)
write_latex_table_row(
        " & & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# Total Employment
Table31Row1(
    dt = total_employment_dt,
    text = "Total Employment",
    scaler = 100000
)
Table31Row2(
    dt = total_employment_dt,
    text = "(per \\$100,000)",
    scaler = 100000
)
write_latex_table_row(
        " & & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# End Table 3.1
add_latex_table_rule(
  rule_type = "bottomrule",
  file_dir = filedir,
  append = TRUE
)
end_latex_table(file_dir = filedir, append = TRUE)
filedir <- NULL
rm(filedir)

# Housekeeping
db_w2_wages_dt <- NULL
per_adult_w2_wages_dt <- NULL
per_adult_total_empl_income_dt <- NULL
per_adult_capital_income_dt <- NULL
has_w2_wages_dt <- NULL
total_employment_dt <- NULL
rm(
    db_w2_wages_dt,
    per_adult_w2_wages_dt,
    per_adult_total_empl_income_dt,
    per_adult_capital_income_dt,
    has_w2_wages_dt,
    total_employment_dt
)